import { WeaSearchGroup,WeaSelect,WeaTools ,WeaErrorPage ,WeaFormItem ,WeaBrowser,WeaDialog,WeaRightMenu} from 'ecCom';
import {inject, observer} from "mobx-react/index";
import { Button , Modal,message} from 'antd';
import {WeaLocaleProvider,WeaDialogFooter} from 'ecCom';
import * as mobx from 'mobx';
// import stores from '../../stores/';
import isEmpty from 'lodash/isEmpty';
import isEqual from 'lodash/isEqual';
import cloneDeep from 'lodash/cloneDeep';
import WfFreeRightDetail from './WfFreeRightDetail';
import WorkflowFreeDrawSvg from './WorkflowFreeDrawSvg';
import OperatorsInfoPanel from './OperatorsInfoPanel';
import ImportFromModel from './ImportFromModel';
import SaveAsTemplate from './saveAsTemplate';
import '../../style/freeTemplateSup.less';

const { toJS } = mobx;
const getLabel = WeaLocaleProvider.getLabel;
let outterThis = null;

/**
isFlowModel : 0 || 1  是否是流转模板
isReadOnlyModel : true | false 是否只读
 */
@observer
class WorkflowFreeContainer extends React.Component{
    constructor(props) {
        super(props);
        this.state = {}
    }
    componentDidMount() {
        const { workflowNewDesignStore , isReadOnlyModel = 'true',isFree , isMobile = '0',closeDialog,reLoadTemplateList,modelSetCloseCB,isFlowModel} = this.props;
        const { setPopOperatorsPanemParams , setCurrentElement_mobile , wfFreeDatas ,mobileChoosedElementIndex ,freeWfTrunkNodes} = workflowNewDesignStore;
        if(isReadOnlyModel == 'true' || isMobile=='1'){
            document.body.addEventListener('click', e => { 
                const classNames = ['geEditor','wf-design-block-groups','wfFrontOperator-header'];//wfFrontOperator-header
                if (e.target && (e.target.nodeName == 'svg' || classNames.indexOf(e.target.className) > -1)) { 
                    setPopOperatorsPanemParams({visible:false});
                    if(e.target.nodeName == 'svg'){
                        window.mxUtils && window.mxUtils.hideWfOperatorInfo();//关闭老流程图的操作者信息面板
                    }
                    if(isMobile=='1'){
                        setCurrentElement_mobile();
                    }
                }             
            }); 
        }
        /*****************/
        let dialog = (typeof top.window.getParentDialog =='function') ? top.window.getParentDialog() : null;
        const _this = this;
        let funct = ()=>{
            message.destroy();
            const { workflowNewDesignStore } = _this.props;
            const { beforeSavedDatas , wfFreeDatas , closeDialogIsConfirmed} = workflowNewDesignStore;
            if(!isEqual(toJS(beforeSavedDatas),toJS(wfFreeDatas)) && !closeDialogIsConfirmed){
                dialog&&dialog.show();
                Modal.confirm({
                    title: getLabel('131329', '信息确认'),
                    content: getLabel(506884,'设置未保存，确定要关闭吗？'),
                    onOk: () => {
                        if(isFlowModel == '1'){
                            closeDialog && closeDialog();
                        }else{
                            workflowNewDesignStore.closeDialogIsConfirmed = true;
                            jQuery('.ant-modal-mask',window.parent.document).hide();
                            jQuery('.ant-modal-wrap',window.parent.document).hide();
                            window.parent.closeWeaDialog && window.parent.closeWeaDialog();
                        }
                    },
                    okText: getLabel(83446,'确定'),
                    okCancel : () => {},
                });
            }else{
                if(isFlowModel == '1'){
                    closeDialog && closeDialog();
                }
            }
            //点× 组件内怎么都会关闭弹框 (特殊控制)
        }
        /*************/
        if(isFlowModel == '1'){
            modelSetCloseCB(funct);
        }
        /**绑定父级dialog事件 */
        if(dialog){
            workflowNewDesignStore.closeDialogIsConfirmed = false;
            window.parent.WfForm&&window.parent.WfForm.getGlobalStore().controlVariableMap('FREE_FLOW_SET_CLOSE_FUNC',funct);
        }
        outterThis = this ;
    }
    
    render(){
        let { location = {} , isOutterFrame = false , isReadOnlyModel = 'true',workflowNewDesignStore,
        isMobile = '0'} = this.props;
        const { popOperatorsPanelParams } = workflowNewDesignStore;
        const { query = {}} = location;
        const { isSingle = false} = query;
        /**
        最后需去掉
         */
        if(!this.props.isReadOnlyModel && query.isReadOnlyModel){
            isReadOnlyModel = query.isReadOnlyModel;
        }
        // ****
        isReadOnlyModel = isReadOnlyModel == 'true' ? true : false;
        let outterStyle = isReadOnlyModel?{height:'100%'} : {}
        return (
            <div style={{height:'100%'}}>
                <div className='wf-design-free-outter-container' 
                    style={outterStyle}>
                    {!isOutterFrame && <WorkflowFreeDrawSvg ecId={`${this && this.props && this.props.ecId || ''}_WorkflowFreeDrawSvg@8yl7u3`} 
                        {...this.props} 
                        {...query}
                        isReadOnlyModel={isReadOnlyModel} 
                    />}
                    {(!isReadOnlyModel && isMobile == '0') && <WfFreeRightDetail ecId={`${this && this.props && this.props.ecId || ''}_WfFreeRightDetail@o3gva6`} {...this.props } {...query}/>}
                    <OperatorsInfoPanel ecId={`${this && this.props && this.props.ecId || ''}_OperatorsInfoPanel@u5b038`} {...popOperatorsPanelParams}/>
                </div>
                {(!isReadOnlyModel && isMobile == '0') && 
                    <div className='free-flowset-bottom-tips'>
                        <div className='tips'>
                            <span>{getLabel(83989,'注：')}</span>
                            <span className="icon-coms-Enlarge"></span>
                            <span>{getLabel(15598,'添加节点')}</span>
                            <span className="icon-coms-delete"></span>
                            <span>{getLabel(15599,'删除节点')}</span>
                            <span className="icon-coms-switch"></span>
                            <span>{getLabel(506885,'更改操作者')}</span>
                        </div>
                        <WeaDialogFooter ecId={`${this && this.props && this.props.ecId || ''}_WeaDialogFooter@3taem8`}
                            buttons={this.getButtons()}
                            moreBtn={{datas:this.getRightMenu()}}
                        />
                    </div>
                }
                <ImportFromModel ecId={`${this && this.props && this.props.ecId || ''}_ImportFromModel@zn8m1m`} {...this.props} {...query}/>
                <SaveAsTemplate ecId={`${this && this.props && this.props.ecId || ''}_SaveAsTemplate@ej4pkx`} {...this.props} {...query}/>
                {(!isReadOnlyModel && isMobile == '1') && <div className="wf-free-deign-mobile">{this.getMobileAddIcon()}</div>}
            </div>
        )
    }
    //移动端调用时页面下方的添加节点icon
    getMobileAddIcon = () => {
        const { workflowNewDesignStore , isMobile = '0'} = this.props;
        const { setPopOperatorsPanemParams , mobileChoosedElement , beSerialNodes , beParallelWithCurNode,mobileChoosedElementIndex} = workflowNewDesignStore;
        const { nodeEntity = {},id='',nodeElement = false,isAddSign=false} = mobileChoosedElement;
        const { nodetype = ''} = nodeEntity;
        if(isEmpty(toJS(mobileChoosedElement)) || nodetype == '3'){ //nodetype==3归档节点
            return;
        }
        let resIcons = [];
        if(isAddSign){//点击加签节点
            resIcons.push(<span className="addIcon" onClick={()=>{
                window.parent.historyRoute.push({
                    pathname: `/req/wfFreeFlowSet/detail`,
                    detailType:'sign',
                    currentGroup: toJS(mobileChoosedElement),
                    pcPublicFreeStore:workflowNewDesignStore
                });
            }}><img src="/images/menu.svg"/></span>);
        }else{
            if(nodeElement){//节点
                resIcons.push(<span className="addIcon" onClick={()=>{
                    if(mobileChoosedElement.trunkNode){
                        beSerialNodes('root',mobileChoosedElementIndex);
                    }else{
                        beSerialNodes(id,mobileChoosedElementIndex);
                    }
                }}><img src="/images/serial.svg"/></span>);//串行添加icon
                if(nodetype!='0'){
                    resIcons.push(<span className="addIcon" onClick={()=>{beParallelWithCurNode(id,mobileChoosedElementIndex)}}>
                    <img src="/images/parall.svg"/></span>);//并行添加icon
                }
            }else{//分支,点击进入设置分支详细信息
                resIcons.push(<span className="addIcon" onClick={()=>{
                    window.parent.historyRoute.push({
                        pathname: `/req/wfFreeFlowSet/detail`,
                        detailType:'branch',
                        currentGroup: toJS(mobileChoosedElement),
                        pcPublicFreeStore:workflowNewDesignStore
                    });
                }}><img src="/images/branch-detail.svg"/></span>);
            }
        }
        
        return resIcons;
    }
    getButtons(){
        const { nodeParams = {} , nodeStyle = {}, workflowNewDesignStore , closeDialog  , location = {},closeDialogFunc, isFlowModel = '0',belongTest = '0'} = this.props;
        const { saveFreeNodeData , beforeSavedDatas , wfFreeDatas , setModelImportDialogShow,closeDialogTrunkFunc,saveAsTemplate,
        allowTemplateImport,globalNextNodeEditPurview,loading = false} = workflowNewDesignStore;
        let btns = [];
        //如果当前操作者无编辑权限则不显示底部按钮
        if(globalNextNodeEditPurview == 0) {
            return btns;
        }
        btns.push(
            <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@bh3f0f@btn1`} type='primary' disabled={loading} onClick={()=>{saveFreeNodeData(this.saveCallBack)}}>{isFlowModel=='0'?getLabel(31103,'保存设置'):getLabel(86,'保存')}</Button>
        );
        if(isFlowModel != '1' && belongTest != '1'){
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@glg6m5@btn2`} type='primary' disabled={loading} onClick={()=>{saveAsTemplate(true)}}>{getLabel(18418,'存为模板')}</Button>
            );
        }
        if(isFlowModel == '1'){
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@a4umw9@btn3`} type='primary' disabled={loading} onClick={()=>{saveAsTemplate(true)}}>{getLabel(131623,'另存为')}</Button>
            );
        }
        if((allowTemplateImport || isFlowModel == '1') && belongTest != '1'){
            btns.push(
                <Button ecId={`${this && this.props && this.props.ecId || ''}_Button@9q7mqu@btn4`} type='primary' disabled={loading} onClick={()=>{setModelImportDialogShow(true)}}>{getLabel(506886,'从模板中导入')}</Button>
            );
        }
        return btns;
    }
    getRightMenu(){
        const { nodeParams = {} , nodeStyle = {}, workflowNewDesignStore , closeDialog  , location = {},closeDialogFunc, isFlowModel = '0',belongTest = '0'} = this.props;
        const { saveFreeNodeData , beforeSavedDatas , wfFreeDatas , setModelImportDialogShow,closeDialogTrunkFunc,saveAsTemplate,
        allowTemplateImport,globalNextNodeEditPurview,loading} = workflowNewDesignStore;
        let rtMenus = [];
        if(globalNextNodeEditPurview == 0) {
            return rtMenus;
        }
        const _this = this;
        rtMenus.push({
            key: "save",
    		icon: <i className="icon-coms-Preservation"/>,
            content:isFlowModel=='0'?getLabel(31103,'保存设置'):getLabel(86,'保存'),
            onClick: key =>{saveFreeNodeData(_this.saveCallBack)},
            disabled:loading
        });
        if(isFlowModel != '1' && belongTest != '1'){
            rtMenus.push({
                key: "saveAsTemplate",
                icon: <i className="icon-coms-Reopen"/>,
                content:getLabel(18418,'存为模板'),
                onClick: key =>{saveAsTemplate(true)},
                disabled:loading
            });
        }
        if(isFlowModel == '1'){
            rtMenus.push({
                key: "saveAs",
                icon: <i className="icon-coms-Reopen"/>,
                content:getLabel(131623,'另存为'),
                onClick: key =>{saveAsTemplate(true)},
                disabled:loading
            });
        }
        if((allowTemplateImport || isFlowModel == '1') && belongTest != '1'){
            rtMenus.push({
                key: "import",
                icon: <i className="icon-coms-Batch-delete"/>,
                content:getLabel(506886,'从模板中导入'),
                onClick: key =>{setModelImportDialogShow(true)},
                disabled:loading
            });
        }
    	return rtMenus;
    }
    saveCallBack = (datas) => {
        const { closeDialog ,closeDialogFunc ,reLoadTemplateList, isFlowModel = '0',workflowNewDesignStore} = this.props;
        const { closeDialogTrunkFunc } = workflowNewDesignStore;
        
        if(isFlowModel == '1'){
            closeDialog && closeDialog();
            reLoadTemplateList && reLoadTemplateList();
        }else{
            /**刷新流程图tab页iframe */
            window.parent.WfForm&&window.parent.WfForm.getGlobalStore().controlVariableMap('FREE_T_KEY',new Date().getTime());
            let oldSrc = jQuery('.req-workflow-map',window.parent.document).attr('src');
            if(oldSrc && oldSrc != ''){
                let arr = oldSrc.split('?');
                let _arr = arr[1].split('&');
                let obj = {};
                _arr.map(v=>{
                    let _p = v.split('=');
                    obj[_p[0]] = _p[1];
                });
                obj['_freekey'] = new Date().getTime();
                _arr = [];
                for(let key in obj){
                    _arr.push(key+'='+obj[key]);
                }
                let newSrc = arr[0] +'?'+ _arr.join('&');
                jQuery('.req-workflow-map',window.parent.document).attr('src',newSrc);
            }
            /*******/
            let dialog = top.window.getParentDialog();
            dialog.callback(datas);
			dialog.hide();
            // dialog.close();
            window.parent.closeWeaDialog && window.parent.closeWeaDialog();
            // window.closeWeaDialog && window.closeWeaDialog();
        }
    }
}

export default WeaTools.tryCatch(React, 
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@ihva59`} msg={ props.error ? props.error : getLabel(383324,' 对不起，该页面异常，请联系管理员 ')+'！'} />,
    {error: ""}
)(WorkflowFreeContainer);

window.wfFreeFlowToMobileUtils = (function(){
    return {
        reloadFreeNodeDatas(data={},workflowNewDesignStore={}){
            const { setReturnGroupValue_mobile , mobileChoosedElementIndex} = workflowNewDesignStore;
            setReturnGroupValue_mobile(data,mobileChoosedElementIndex);
        },
        saveFreeDatas_mobile(workflowNewDesignStore={}){
            const { saveFreeNodeData } = workflowNewDesignStore;
        },
        getAllFreeDatas_mobile(_workflowNewDesignStore={}){
            const { workflowNewDesignStore = {} } = outterThis.props;
            const { wfFreeDatas , circulationOrginNode , currentPostParams , currentAddDataId , deleteIds , currentValidStartNodeId} = workflowNewDesignStore;

            const cloneDatas = cloneDeep(mobx.toJS(wfFreeDatas));
            let endId = circulationOrginNode.endOrginNodeId == '' ? currentPostParams.isFree == '1' ?
            circulationOrginNode.nextOrginNode : circulationOrginNode.startOrginNodeId : circulationOrginNode.endOrginNodeId;

            let postChatDatas = cloneDatas[currentValidStartNodeId] ? JSON.stringify(cloneDatas[currentValidStartNodeId][0]) : '{}';
            const submitParams = {
                ...currentPostParams,
                maxGroupNum : currentAddDataId,
                chartDatas: postChatDatas,
                deleteIds: deleteIds.join(','),
                freeStartNodeid: circulationOrginNode.startOrginNodeId,
                freeEndNodeid: endId,
                // ...params,
            };

            return submitParams;
        }
    }
})();